package com.hankol.community

import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.activity.BaseActivity
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.extension.load
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.share.SharePopupWindow
import com.google.android.material.appbar.AppBarLayout
import com.baselibrary.utils.EmptyViewUtil
import com.hankol.community.adapter.ForumClassifyListAdapter
import com.hankol.community.arouter.CommunityHelp
import com.hankol.community.bean.ForumClassifyInfoBean
import com.hankol.community.bean.ForumListBean
import com.hankol.community.bean.ShowShare2Bean
import com.hankol.community.databinding.ActivityForumClassifyBinding
import com.hankol.community.viewmodel.CommunityViewModel
import java.util.*


/**
 * @description 讲坛分类
 *@author wxp
 */
@Route(path = ActivityRouter.COMMUNITY.FORUM_CLASSIFY)
class ForumClassifyActivity : BaseActivity() {
    var id = 0
    var page = 1
    private var hasnext: Boolean = false
    private val adapter by lazy { ForumClassifyListAdapter() }
    private val mLayoutManager by lazy { LinearLayoutManager(this) }
    private lateinit var binding: ActivityForumClassifyBinding
    private lateinit var mViewModel: CommunityViewModel
    private var mDataBean: ForumClassifyInfoBean? = null
    private var mShowSharePop: SharePopupWindow? = null
    val communityHelp: CommunityHelp = ActivityRouter.getARouterInterface(ActivityRouter.COMMUNITY.COMMUNITY_HELP)

    //曝光数
    var exposureCnt = 0

    override fun getLayoutId(): Int {
        return R.layout.activity_forum_classify
    }

    override fun init() {
        //获取页面开始时间
        SensorsDataManager.instance.onCreateTime()
        SensorsDataManager.instance.setFormPagePos("讲坛分类")
        binding = getDataBinding<ActivityForumClassifyBinding>()
        mViewModel = getActivityViewModelProvider(this).get(CommunityViewModel::class.java)
        if (intent.extras.checkNotNull()) {
            if (ARouterUtils.parseParams(intent.extras!!, "id").isNotEmpty()) {
                id = ARouterUtils.parseParams(intent.extras!!, "id")[0].toInt()
            }
        }
        initView()
        reqDetailData()
        loadData()
        initListener()
        initObserver()
    }

    private fun initView() {
        BannerSizeUtil.setBannerSizeValue(binding.imgCover,347,129)
        binding.rvForumClassify.adapter = adapter
        binding.rvForumClassify.layoutManager = mLayoutManager
        //曝光监听
        binding.rvForumClassify.addOnScrollListener(object : RecyclerViewExposureListener() {
            override fun exposureView(view: View?, index: Int) {
                exposureCnt = index.plus(2)
            }
        })
    }

    private fun initObserver() {
        //讲坛分类 详情
        mViewModel.forumClassDetailLD.observe(this, Observer {
            setDataInfo(it)
        })

        mViewModel.forumMld.observe(this, Observer {
            hideLoadingDialog()
            binding.smartRefresh.finishRefresh()
            if (it == null || it.data?.size == 0) {
                //无数据
                if (page != 1) {
                    binding.smartRefresh.finishLoadMore()
                }
                adapter.emptyView = EmptyViewUtil.getEmptyView(Constants.DYNAMIC_TYPE_FORUM_CLASSIFY, binding.rvForumClassify)
            } else {
                if (it.data != null) {
                    hasnext = it.totalPage != adapter.data.size
                    binding.smartRefresh.finishLoadMore()
                    if (page == 1) {
                        adapter.setNewData(it.data)
                    } else {
                        adapter.addData(it.data!!)
                    }
                    page++
                }
            }
        })
        //请求好友列表
//        mViewModel.friendLiveData.observe(this, Observer {
//            mShowSharePop?.setShareFriendAdapter(mViewModel.changeFriend(it))
//        })
    }

    private fun initListener() {
        binding.backImageView.setOnClickListener { finish() }
        binding.ablTop.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
            val offset = ScreenUtils.dpToPx(158) + binding.tvPeriodsPlayNum.height
            if (-verticalOffset in 0..offset) {
                binding.tvTopTitle.visibility = View.GONE
            } else {
                binding.tvTopTitle.visibility = View.VISIBLE
            }
        })
        adapter.setOnItemClickListener { adapter, view, position ->
            if (!DoubleUtils.isFastDoubleClick()) {
                val bean = adapter.data[position] as ForumListBean
                //进入对应详情页面
                val hashMap = HashMap<String, Any>()
                hashMap["pulpitId"] = bean.id.toLong()
                ARouterUtils.jump(ActivityRouter.COMMUNITY.COMMUNITY_PULPITHOME, hashMap)
            }
        }
        binding.ivTopShare.setOnClickListener {
            //分享弹窗
            mDataBean?.let {
                mShowSharePop = mViewModel.showShare(articleBean2showShare(it), this, communityHelp,false,false)
            }
        }
        binding.smartRefresh.setOnRefreshListener {
            page = 1
            loadData()
            reqDetailData()
        }
        binding.smartRefresh.setOnLoadMoreListener {
            if (hasnext) {
                loadData()
            } else {
                binding.smartRefresh.finishLoadMore()
            }
        }
    }

    fun loadData() {
        showLoadingDialog()
        mViewModel.reqForumList(id, page)
    }

    fun reqDetailData() {
        mViewModel.reqForumClassDetail(id)
    }

    private fun setDataInfo(bean: ForumClassifyInfoBean?) {
        mDataBean = bean
        bean?.let {
            binding.tvTitle.text = it.title.checkValue()
            binding.tvTopTitle.text = it.title.checkValue()
            binding.tvPeriodsPlayNum.text = "${it.number} 期 · ${NumberUtils.formatBigNum("${it.allWatchNum}")} 播放"
            //封面
            binding.imgCover.load(this, it.detailImage.checkValue())
            SensorsDataManager.instance.forumClick("${id}",it.title.checkValue())
        }
    }

    private fun articleBean2showShare(bean: ForumClassifyInfoBean): ShowShare2Bean {
        return ShowShare2Bean().apply {
            id = bean.id
            showType = 1
            cover = bean.cover
            title = bean.title.checkValue()
            content = ""
            url = Constants.FORUM_SHARE_URL + id
        }
    }

    override fun onPause() {
        super.onPause()
        //获取页面结束时间
        SensorsDataManager.instance.onDestroyTime()
        if (SensorsDataManager.instance.getBrowseTime() != 0L) {
            SensorsDataManager.instance.browseClassForum(mDataBean?.title.checkValue(), exposureCnt.div(adapter.data.size.toFloat()).toInt())
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //获取页面结束时间
        SensorsDataManager.instance.onDestroyTime()
        if (SensorsDataManager.instance.getBrowseTime() != 0L) {
            SensorsDataManager.instance.browseClassForum(mDataBean?.title.checkValue(), exposureCnt.div(adapter.data.size.toFloat()).toInt())
        }

    }
}